package com.hhss.qishi.controller.sys;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hhss.qishi.config.constant.ModuleConstants;
import com.hhss.qishi.config.constant.OperateConstants;
import com.hhss.qishi.config.log.webLog.WebLog;
import com.hhss.qishi.config.pagehelper.PageVO;
import com.hhss.qishi.entity.system.User;
import com.hhss.qishi.service.system.UserService;
import com.hhss.qishi.utils.ConvertPageUtil;
import com.hhss.qishi.utils.MD5Util;
import com.hhss.qishi.utils.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * 用户控制器
 * @author hhss
 * @date 2018年7月19日
 */
@RestController
@RequestMapping("users")
public class UserController {
	
	@Autowired
    private UserService userService;
	
	@RequestMapping(value = "/", method = RequestMethod.GET)
    public Map<String, Object> getList(User user) {
        Page<User> page = PageHelper.startPage(user.getPage(), user.getLimit());
        userService.getList(user);
        PageVO<User> vo = PageVO.build(page);
        return ConvertPageUtil.Convert(vo);
    }

	@RequestMapping(value = "/", method = RequestMethod.POST)
	@WebLog(module = ModuleConstants.MODULE_USER, operate = OperateConstants.OPR_ADD)
	public int add(User user) {
		// 赋予盐值
		user.setSalt(UUIDUtil.getUUIDShort());
		// 原密码+盐值的MD5加密
		user.setPassword(MD5Util.MD5(user.getPassword() + user.getSalt()));
		return userService.add(user);
	}
	
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public User getById(@PathVariable Long id) {
		return userService.getById(id);
	}
	
	@RequestMapping(value = "/", method = RequestMethod.PUT)
	@WebLog(module = ModuleConstants.MODULE_USER, operate = OperateConstants.OPR_UPDATE)
	public int update(User user) {
		if(!StringUtils.isEmpty(user.getPassword())){
			// 原密码+盐值的MD5加密
			user.setPassword(MD5Util.MD5(user.getPassword() + user.getSalt()));
		}
		return userService.updateById(user);
	}
	
	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	@WebLog(module = ModuleConstants.MODULE_USER, operate = OperateConstants.OPR_DELETE)
	public int deleteById(@PathVariable Long id) {
		return userService.deleteById(id);
	}
	
	@RequestMapping(value = "/roles", method = RequestMethod.GET)
	public User getUserRoleById(User user){
		return userService.getUserRoleById(user);
	}
	
	@RequestMapping(value = "/getUserInfo", method = RequestMethod.GET)
    public Object getUserInfo(){
          return SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }
}